<template>
  <Combination
    ref="comUdpRef"
    class="price-udp"
    :items="comItem"
    :comData="ruleForm.data"
    :rules="comRules"
    :size="5"
    :isEndAdd="true"
    @data-plus="dataPlus"
  ></Combination>
</template>

<script lang="ts" setup name="price-udp">
import type { FormRules } from 'element-plus';
import Combination from '@/components/combination/combination.vue';
import { IS_DECIMAL_4 } from '@/utils/verify';
import { optionsP, visibleChangeStart, visibleChangeEnd } from './price';

interface Props {
  protocolVersion?: string;
}
const prop = withDefaults(defineProps<Props>(), {
  protocolVersion: '',
});

const comUdpRef = ref();

let options = reactive({
  sTimes: [] as any,
  eTimes: [] as any,
});
options.sTimes = optionsP.sTimes;
options.eTimes = optionsP.eTimes;

const ruleForm = reactive({
  data: [] as any,
});

// 开始时间下拉是重置下拉数据
const visibleChangeS = (e: any, index: number, form: any) => {
  if (e) {
    visibleChangeStart(e, index, form);
    comUdpRef.value?.setOptions(index, 0, options.sTimes);
  }
};

// 结束时间下拉是重置下拉数据
const visibleChangeE = (e: any, index: number, form: any) => {
  if (e) {
    visibleChangeEnd(e, index, form);
    comUdpRef.value?.setOptions(index, 1, options.eTimes);
  }
};

// 判断是否覆盖24小时，覆盖就不再增加
const checkTime = (rule: any, value: any, callback: any) => {
  const index = rule.field.split('.[')[1].split(']')[0];
  const form = comUdpRef.value?.getData();
  let arr = [] as any;
  form.forEach((item: any, inx: number) => {
    if (index !== inx) {
      for (let i = Number(item.startTime); i < Number(item.endTime); i++) {
        arr.push(i);
      }
    }
  });
  if (arr.length >= 48) {
    comUdpRef.value?.setFlagAdd(true);
  } else {
    comUdpRef.value?.setFlagAdd(false);
  }
  callback();
};
// 增加选项时判断是否覆盖24小时，覆盖就不再增加
const getTimeArr = (data: any) => {
  let arr = [] as any;
  data.forEach((item: any) => {
    for (let i = Number(item.startTime); i < Number(item.endTime); i++) {
      arr.push(i);
    }
  });
  return arr;
};

const comItem = reactive([
  {
    comName: 'select',
    label: '开始时间',
    labelWidth: 80,
    prop: 'startTime',
    width: 140,
    props: {
      clearable: false,
      icon: 'Clock',
      options: options.sTimes,
      visibleChange: visibleChangeS,
    },
  },
  {
    comName: 'select',
    label: '结束时间',
    labelWidth: 80,
    prop: 'endTime',
    width: 140,
    props: {
      clearable: false,
      icon: 'Clock',
      options: options.eTimes,
      visibleChange: visibleChangeE,
    },
  },
  {
    comName: 'input',
    label: '电费',
    labelWidth: 80,
    prop: 'pricePower',
    width: 180,
    props: {
      append: '元/度',
      maxlength: 10,
      placeholder: '精确到4位小数',
    },
  },
  {
    comName: 'input',
    label: '服务费',
    labelWidth: 80,
    prop: 'priceService',
    width: 180,
    props: {
      append: '元/度',
      maxlength: 10,
      placeholder: '精确到4位小数',
    },
  },
]);
const comRules = reactive<FormRules>({
  startTime: [
    { required: true, message: '请选择开始时间', trigger: ['blur', 'change'] },
    { validator: checkTime, trigger: 'change' },
  ],
  endTime: [
    { required: true, message: '请选择结算时间', trigger: ['blur', 'change'] },
    { validator: checkTime, trigger: 'change' },
  ],
  pricePower: [
    { required: true, message: '请输入电费', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_4,
      message: '请输入正确的电费，精确到4位小数',
      trigger: 'blur',
    },
  ],
  priceService: [
    { required: true, message: '请输入服务费', trigger: 'blur' },
    {
      pattern: IS_DECIMAL_4,
      message: '请输入正确的电费，精确到4位小数',
      trigger: 'blur',
    },
  ],
});

const dataPlus = (index: number, item: any) => {
  if (item[index].endTime === '48') return;
  let flag = false;
  for (let i = 0; i < item.length; i++) {
    const it = item[i];
    if (it.startTime && item[index].endTime === it.startTime) {
      flag = true;
      break;
    }
  }
  if (flag) return;
  item[index + 1].startTime = item[index].endTime;
};

const getData = async () => {
  if (!comUdpRef.value) return;
  try {
    await Promise.all([comUdpRef.value.validate()]);
  } catch (fields: any) {
    for (const key in fields) {
      if (fields[key]) {
        comUdpRef.value.scrollToField(key);
        break;
      }
    }
    return false;
  }
  const data = comUdpRef.value?.getData();
  if (
    data.length === 1 &&
    (!data[0].startTime ||
      !data[0].endTime ||
      !data[0].pricePower ||
      !data[0].priceService)
  )
    return false;
  let arr = getTimeArr(data);
  if (arr.length < 48) {
    // 未覆盖24小时提示
    ElMessage({
      showClose: true,
      message: '充电单价时段未覆盖24小时',
      type: 'warning',
    });
    comUdpRef.value.scrollToField('data.[0][startTime]');
    return false;
  }
  let flag = false;
  const sarr = arr.sort();
  for (let i = 0; i < sarr.length; i++) {
    if (sarr[i] == sarr[i + 1]) {
      flag = true;
      break;
    }
  }
  if (flag) {
    // 有重复
    ElMessage({
      showClose: true,
      message: '充电单价时段有重复，请检查',
      type: 'warning',
    });
    comUdpRef.value.scrollToField('data.[0][startTime]');
    return false;
  }
  let resp = [] as any;
  data.forEach((item: any, inx: number) => {
    resp.push({
      protocolVersion: prop.protocolVersion, //协议版本
      identification: String(inx + 1), // 标识（1、2、3、4、5）
      startTime: item.startTime,
      endTime: item.endTime,
      startTimeStr: options.sTimes.find(
        (temp: any) => temp.value === item.startTime
      ).label,
      endTimeStr: options.eTimes.find(
        (temp: any) => temp.value === item.endTime
      ).label,
      pricePower: item.pricePower,
      priceService: item.priceService,
    });
  });
  return resp;
};

const setData = (data: any) => {
  ruleForm.data = [];
  data.forEach((item: any) => {
    ruleForm.data.push({
      startTime: String(item.startTime),
      endTime: String(item.endTime),
      pricePower: String(item.pricePower),
      priceService: String(item.priceService),
    });
  });
};

defineExpose({
  getData,
  setData,
});
</script>

